import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CompareWordsIgnoreCase {
    public static void main(String[] args) {
        String filePath1 = "file1.txt"; // 替换为您的第一个文件路径
        String filePath2 = "file2.txt"; // 替换为您的第二个文件路径

        try {
            ArrayList<String> words1 = extractWordsFromFile(filePath1);
            ArrayList<String> words2 = extractWordsFromFile(filePath2);

            Set<String> commonWords = new HashSet<>(words1);
            System.out.println(commonWords.size());
            System.out.println( new ArrayList<>(words2));
            System.out.println( new HashSet<>(words2).size());

            commonWords.retainAll(words2); // 获取交集

            Set<String> uniqueWords1 = new HashSet<>(words1);
            uniqueWords1.removeAll(words2); // 获取差集 (words1 - words2)
            System.out.println(commonWords.size());

            Set<String> uniqueWords2 = new HashSet<>(words2);
            uniqueWords2.removeAll(words1); // 获取差集 (words2 - words1)

            System.out.println("Common words: " + commonWords);
            System.out.println("Unique words in file1: " + uniqueWords1);
            System.out.println("Unique words in file2: " + uniqueWords2);

        } catch (IOException e) {
            System.err.println("Error processing files: " + e.getMessage());
        }
    }

    private static ArrayList<String> extractWordsFromFile(String filePath) throws IOException {
        ArrayList<String> words = new ArrayList();
        String regex = "[^\\s]+"; // 匹配单词
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // 不区分大小写
        //Pattern pattern = Pattern.compile(regex); // 区分大小写

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                while (matcher.find()) {
                    words.add(matcher.group().toLowerCase()); // 将单词转换为小写并添加到集合中
                }
            }
        }
        return words;
    }
}
